package com.xiaoshuidi.cloud.module.report.xxljob;

import com.xiaoshuidi.cloud.framework.tenant.core.aop.TenantIgnore;
import com.xiaoshuidi.cloud.module.report.dal.DO.report.OwnerIncomeSummaryReportDO;
import com.xiaoshuidi.cloud.module.report.service.finance.OwnerIncomeDetailReportService;
import com.xiaoshuidi.cloud.module.report.service.finance.OwnerIncomeSummaryReportService;
import com.xiaoshuidi.cloud.module.report.utils.DateUtils;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 成本汇总处理job每天凌晨6跑一次
 * 需将汇总明细的数据进行再次汇总
 */
@Component
@Slf4j
public class OwnerIncomeSummaryHandleJob {

    @Resource
    private OwnerIncomeDetailReportService ownerIncomeDetailReportService;

    @Resource
    private OwnerIncomeSummaryReportService ownerIncomeSummaryReportService;

    @XxlJob("ownerIncomeSummaryHandleJob")
    @TenantIgnore
    public void execute() {
        //获取当月所有的明细
        String currentMonth = DateUtils.getYesterdayMonth();

        List<OwnerIncomeSummaryReportDO> incomeSummaryReportDOS = ownerIncomeDetailReportService.selectDetailsInCurrentMonthGroupByApartmentId(currentMonth);

        if(CollectionUtils.isNotEmpty(incomeSummaryReportDOS)){
            List<OwnerIncomeSummaryReportDO> summaryReportDOList = ownerIncomeSummaryReportService.selectSumByCurrentMonth(currentMonth);
            if(CollectionUtils.isEmpty(summaryReportDOList)){
                ownerIncomeSummaryReportService.batchInsert(incomeSummaryReportDOS);
            }else {
                List<String> areas = summaryReportDOList.stream().map(OwnerIncomeSummaryReportDO::getArea).collect(Collectors.toList());
                List<OwnerIncomeSummaryReportDO> updateList = incomeSummaryReportDOS.stream().filter(e -> areas.contains(e.getArea())).collect(Collectors.toList());
                List<OwnerIncomeSummaryReportDO> insertList = incomeSummaryReportDOS.stream().filter(e -> !areas.contains(e.getArea())).collect(Collectors.toList());
                if(CollectionUtils.isNotEmpty(updateList)){
                    updateList.forEach(e->{
                        summaryReportDOList.forEach(report->{
                            if(e.getArea().equals(report.getArea())){
                                e.setId(report.getId());
                            }
                        });
                    });
                    ownerIncomeSummaryReportService.batchUpdate(updateList);
                }
                if(CollectionUtils.isNotEmpty(insertList)){
                    ownerIncomeSummaryReportService.batchInsert(insertList);
                }
            }
        }
    }

}